<template>
  <div>
    <!--    文件信息-->
    <el-card style="height: 780px" v-loading="fileLoading">
      <div slot="header" class="search-header">
        <div class="show_title button-group" style="margin-bottom: 5px">文件列表：</div>
        <div class="button-group" style="margin-left: auto">
          <el-button type="primary" size="mini" @click="downloadFiles" v-if="downloadFlag">下载</el-button>
          <el-button type="primary" size="mini" @click="downloadChange" v-if="fileList.length > 0">
            {{ downloadFlag ? '取消' : '批量下载' }}
          </el-button>
        </div>
      </div>
      <div class="engs-container" ref="fileContainer">
        <div
          class="eng-row"
          v-for="file in fileList"
          :key="file.id"
          @click="selectFile(file)"
          @dblclick="openFile(file)"
          :class="{ selected: file === selectedFile }"
        >
          <input type="checkbox" v-model="file.selected" @click.stop="selectFiles(file)" v-if="downloadFlag"/>
          <i class="folder-icon file-folder-icon"></i>
          <div slot="reference" class="name-wrapper">
            <span size="medium" class="folder-name" style="display:inline-block;width:100%;word-wrap:break-word;white-space:normal;">{{ file.filename }}</span>
          </div>
        </div>
      </div>
      <div class="pagination-container">
        <!-- 分页信息 -->
        <el-pagination
          @size-change="handleSizeChangeFile"
          @current-change="handleCurrentChangeFile"
          :current-page.sync="fileQueryParams.pageNum"
          :page-size.sync="fileQueryParams.pageSize"
          layout="total, prev, pager, next"
          :total="fileTotal"
        ></el-pagination>
      </div>
    </el-card>
    <!--    MP4预览-->
    <el-dialog :visible.sync="videoDialogVisible" center v-loading="loadingMp4" title="文件详情" :before-close="handleVideoDialogClose">
      <video :src="videoUrl"
             autoplay="autoplay"
             ref="vueRef"
             controls width="100%">
        Your browser does not support the video tag.
      </video>
    </el-dialog>
    <!--    PDF预览-->
    <el-dialog :visible.sync="pdfDialogVisible" title="文件详情" :width="dialogWidth" center>
      <embed :src="pdfUrl" type="application/pdf" width="100%" height="1000px">
    </el-dialog>
    <!--    图片预览-->
    <el-image-viewer v-if="imgDialogVisible" :zIndex="Number(99999)" :url-list="canvasList"
                     :on-close="closeImgViewer"/>
  </div>
</template>

<script>
import {downloadMore, getPdf, getType, listFileInfo} from "@/api/system/fileinfo";
import Tiff from 'tiff.js'

export default {
  props: {
    selectedOneVolume: Object
  },
  components: {
    'el-image-viewer': () => import('element-ui/packages/image/src/image-viewer')
  },
  data() {
    return {
      fileList: [], //文件列表
      fileTotal: 0, //文件总数
      selectedFile: null,
      fileQueryParams: {
        pageNum: 1,
        pageSize: 20,
        volumeid: null,
        filename: null,
      },
      fileLoading: false,

      blobImage: "", //图片url
      canvasList: [],
      pdfUrl: "", // 存储PDF文件的URL地址
      videoUrl: "", // 存储视频文件的URL地址
      loadingMp4: false, //MP4加载动画
      pdfDialogVisible: false, // 控制弹窗的显示与隐藏
      imgDialogVisible: false, // 控制弹窗的显示与隐藏
      videoDialogVisible: false, // 控制弹窗的显示与隐藏
      dialogWidth: "70%", // 弹窗的宽度
      dialogHeight: "80vh",
      selectedFiles: [], // 存储被选中的文件的数组
      downloadFlag: false, //下载显示勾选框
    };
  },
  watch: {
    selectedOneVolume(newValue) {
      this.fileQueryParams.volumeid = newValue.id;
      this.getFileList();
    }
  },
  methods: {
    //获取文件信息
    getFileList() {
      this.fileLoading = true;
      listFileInfo(this.fileQueryParams).then((response) => {
        response.rows.forEach((file) => {
          file.selected = false; // 为每个数据对象添加selected属性，初始值为false
        });
        setTimeout(() => {
          this.fileList = response.rows;
          this.fileTotal = response.total;
          this.fileLoading = false;
        }, 300);
      }).catch((error) => {
        this.$message.error("获取文件信息失败:" + error);
        this.fileLoading = false;
      });
    },
    //选中文件
    selectFile(file) {
      this.selectedFile = file;
      this.$emit('selectFile', file);
    },
    //选中多个文件
    selectFiles(file) {
      // 如果文件已经选中，取消选中并从selectedFiles数组中移除
      const index = this.selectedFiles.findIndex(selectedFile => selectedFile.id === file.id);
      if (file.selected) {
        file.selected = false;
        if (index !== -1) {
          this.selectedFiles.splice(index, 1); // 使用splice方法移除指定索引的元素
        }
      } else {
        // 如果文件未选中，选中并添加到selectedFiles数组中
        file.selected = true;
        this.selectedFiles.push(file);
      }
    },
    //展开/关闭下载
    downloadChange() {
      this.fileList.forEach((file) => {
        file.selected = false; // 为每个数据对象添加selected属性，初始值为false
      });
      this.selectedFiles = [];
      this.downloadFlag = !this.downloadFlag;
    },
    //下载多个文件
    downloadFiles() {
      if (this.selectedFiles.length === 0) {
        this.$message({
          message: '请先选择要下载的文件！',
          type: 'warning'
        });
      } else if (this.selectedFiles.length === 1) {
        this.selectedFiles.forEach(file => {
          this.downloadOneFile(file);
        })
      } else {
        let ids = [];
        this.selectedFiles.forEach(file => {
          let newId = file.id.replace(/\//g, "++");
          ids.push(newId)
        })
        downloadMore(ids).then((response) => {
          // 处理接收到的二进制ZIP文件数据
          const blob = new Blob([response], {type: "application/zip"});
          const url = window.URL.createObjectURL(blob);
          // 创建一个下载链接并触发点击以下载ZIP文件
          const a = document.createElement('a');
          a.href = url;
          a.download = 'downloaded.zip';
          a.style.display = 'none';
          document.body.appendChild(a);
          a.click();
          window.URL.revokeObjectURL(url);
          this.selectedFiles = []; // 清除多选信息
        });
      }
    },
    // 下载单个文件名打开文件
    downloadOneFile(file) {
      getType(file).then((response) => {
        const fileType = response.toLowerCase();
        getPdf(file).then( res => {
          // 处理接收到的二进制ZIP文件数据
          const blob = new Blob([res], {type: "application/pdf"});
          const url = window.URL.createObjectURL(blob);
          // 创建一个下载链接并触发点击以下载ZIP文件
          const a = document.createElement('a');
          a.href = url;
          a.download = file.filename.slice(0, str.lastIndexOf('.')) + "." + fileType;
          a.style.display = 'none';
          document.body.appendChild(a);
          a.click();
          window.URL.revokeObjectURL(url);
        })
      })
    },
    // 双击文件名打开文件
    openFile(file) {
      getType(file).then((response) => {
        const fileType = response.toLowerCase(); // 转换为小写以确保比较不区分大小写
        if (fileType === 'pdf') {
          this.openPDF(file);
        } else if (fileType === 'jpg' || fileType === 'jpeg' || fileType === 'tif' || fileType === 'gif' || fileType === 'png') {
          this.openImg(file);
        } else if (fileType === 'tiff') {
          this.openTiff(file);
        } else if (fileType === 'mp4') {
          this.openMp4(file);
        }
      });
    },

    openTiff(file) {
      this.canvasList = [];
      this.fileForm = file;
      getPdf(this.fileForm).then((response) => {
        var tiff = new Tiff({buffer: response})
        for (let i = 0, len = tiff.countDirectory(); i < len; ++i) {
          tiff.setDirectory(i)
          var imgs = tiff.toDataURL() // 转化成base64
          if (imgs) {
            this.canvasList.push(imgs)
            this.imgDialogVisible = true;
          }
        }
        console.log(this.canvasList)
      }).catch((error) => {
        console.error("获取图片时出错:", error);
      });
    },
    //打开PDF
    openPDF(file) {
      this.fileForm = file; // 将文件信息保存到fileForm中，以便在getPdf函数中使用
      getPdf(this.fileForm)
        .then((response) => {
          const blob = new Blob([response], {type: "application/pdf"});
          this.pdfUrl = URL.createObjectURL(blob);
          this.pdfDialogVisible = true; // 显示弹窗
        })
        .catch((error) => {
          console.error("Error occurred while fetching the PDF:", error);
        });
    },

    //打开图片
    openImg(file) {
      this.canvasList = [];
      this.fileForm = file; // 将文件信息保存到fileForm中，以便在getPdf函数中使用
      getPdf(this.fileForm)
        .then((response) => {
          const blob = new Blob([response], {type: "image/jpeg"});
          this.blobImage = URL.createObjectURL(blob);
          this.canvasList.push(URL.createObjectURL(blob))
          this.imgDialogVisible = true; // 显示弹窗
        })
        .catch((error) => {
          console.error("获取图片时出错:", error);
        });
    },

    openMp4(file) {
      this.videoDialogVisible = true; // 显示弹窗
      this.loadingMp4 = true;
      getPdf(file).then((response) => {
        const blob = new Blob([response], {type: "video/mp4"});
        this.videoUrl = URL.createObjectURL(blob);
      }).catch((error) => {
        console.error("获取文件时出错:", error);
      });
      this.loadingMp4 = false;
    },
    handleVideoDialogClose(done){
      this.$refs.vueRef.pause();
      done(); // 调用 done() 完成弹窗的关闭操作
    },
    closeImgViewer() {
      this.imgDialogVisible = false
    },
    handleSizeChangeFile(pageSize) {
      this.fileQueryParams.pageSize = pageSize;
      this.getFileList();
    },
    handleCurrentChangeFile(currentPage) {
      this.fileQueryParams.pageNum = currentPage;
      this.getFileList();
    },
  },
};
</script>

<style>
/* 公共样式 */
.search-header {
  display: flex;
  align-items: center;
}

.my_input {
  margin-left: auto;
  width: 30%;
  margin-right: 5px;
}

.dialog-content {
  display: flex;
  flex-direction: column;
}

.my_button {
  display: flex;
  justify-content: flex-end;
  margin-bottom: 10px;
  margin-left: 85%;
}

.button-group {
  display: flex;
  justify-content: center;
  margin-top: 10px;
}

.engs-container {
  height: 600px;
  overflow-y: auto;
}

.eng-row {
  flex-basis: 100%;
  margin-bottom: 10px;
  display: flex;
  align-items: center;
}

.eng-row:hover {
  cursor: pointer;
  background-color: #e5f3ff;
}

.pagination-container {
  margin-top: 10px;
}

.folder-icon {
  flex-shrink: 0;
  width: 20px;
  height: 20px;
  margin-right: 5px;
  background-size: cover;
}

.folder-name {
  flex-grow: 1;
  font-size: 14px;
  color: #333;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.show_title {
  font-weight: bold;
  font-size: 1.2rem;
  color: rgb(26, 115, 198);
}

.dialog-content {
  display: flex;
  flex-direction: column;
}

.button-group {
  display: flex;
  justify-content: space-between;
  margin-bottom: 10px;
}

/* 不同图标的样式 */
.eng-folder-icon {
  background-image: url("~@/assets/icons/folder/eng-icon.png");
}

.volume-folder-icon {
  background-image: url("~@/assets/icons/folder/volume-icon.png");
}

.file-folder-icon {
  background-image: url("~@/assets/icons/folder/file-icon.png");
}

/* 选中状态的样式 */
.selected {
  /*box-shadow: 0 0 5px rgba(0, 0, 0, 0.3);*/
  background-color: #cce8ff;
}
</style>

